package com.sanqing.iframe;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import com.sanqing.model.Item;
import com.sanqing.model.MapPz;
import com.sanqing.dao.Dao;
import com.sanqing.model.BookInfo;
import com.sanqing.model.BookType;

public class BookInfoFrame extends JInternalFrame {
    private JTable table;
    private String[] columnNames;
    private Item item;
    private Map<Integer, Item> IdToItem = new HashMap<>();
    private JComboBox bookTypeFilter;
    private DefaultComboBoxModel bookTypeModel;
    private JPopupMenu popupMenu; // 右键菜单

    private Object[][] getFileStates(List list) {
        String[] columnNames = { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "语言", "出版日期", "价格", "库存数量" };
        Object[][] results = new Object[list.size()][columnNames.length];
        for (int i = 0; i < list.size(); i++) {
            BookInfo bookinfo = (BookInfo) list.get(i);
            results[i][0] = bookinfo.getISBN();
            Integer typeId = bookinfo.getTypeid();
            String bookTypeName = MapPz.getIdToName().get(typeId);
            results[i][1] = bookTypeName;
            results[i][2] = bookinfo.getBookname();
            results[i][3] = bookinfo.getWriter();
            results[i][4] = bookinfo.getTranslator();
            results[i][5] = bookinfo.getPublisher();
            results[i][6] = bookinfo.getLanguage();
            results[i][7] = bookinfo.getDate();
            results[i][8] = bookinfo.getPrice();
            results[i][9] = bookinfo.getNumber();
        }
        return results;
    }

    public BookInfoFrame() {
        super();
        final BorderLayout borderLayout = new BorderLayout();
        getContentPane().setLayout(borderLayout);
        setIconifiable(true);
        setClosable(true);
        setTitle("图书查看");
        setBounds(20, 100, 850, 406);

        // 初始化右键菜单
        initPopupMenu();

        // 顶部筛选面板
        final JPanel filterPanel = new JPanel();
        filterPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
        getContentPane().add(filterPanel, BorderLayout.NORTH);

        final JLabel filterLabel = new JLabel();
        filterLabel.setHorizontalAlignment(SwingConstants.CENTER);
        filterLabel.setText("图书类别:");
        filterPanel.add(filterLabel);

        bookTypeFilter = new JComboBox();
        bookTypeModel = (DefaultComboBoxModel) bookTypeFilter.getModel();
        bookTypeModel.addElement(new Item(-1, "全部")); // 添加"全部"选项
        
        List list = Dao.selectBookCategory();
        for (int i = 0; i < list.size(); i++) {
            BookType booktype = (BookType) list.get(i);
            item = new Item();
            item.setId(booktype.getId());
            item.setName((String) booktype.getTypeName());
            bookTypeModel.addElement(item);
            IdToItem.put(item.getId(), item);
            MapPz.getNameToId().put(item.getName(), item.getId());
        }
        
        filterPanel.add(bookTypeFilter);
        
        // 添加筛选事件
        bookTypeFilter.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                filterBooks();
            }
        });

        // 表格区域
        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        Object[][] results = getFileStates(Dao.selectBookInfo());
        columnNames = new String[] { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "语言", "出版日期", "价格", "库存数量" };
        table = new JTable(results, columnNames);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.addMouseListener(new TableListener());
        scrollPane.setViewportView(table);

        // 底部按钮面板
        final JPanel bottomPanel = new JPanel();
        getContentPane().add(bottomPanel, BorderLayout.SOUTH);

        setVisible(true);
    }

    // 初始化右键菜单
    private void initPopupMenu() {
        popupMenu = new JPopupMenu();
        JMenuItem copyISBNItem = new JMenuItem("复制ISBN");
        copyISBNItem.addActionListener(e -> copySelectedRowISBN());
        popupMenu.add(copyISBNItem);
        
        // 新增右键菜单项
        JMenuItem copyBookNameItem = new JMenuItem("复制图书名称");
        copyBookNameItem.addActionListener(e -> copySelectedRowField(2));
        popupMenu.add(copyBookNameItem);
        
        JMenuItem copyCategoryItem = new JMenuItem("复制图书类别");
        copyCategoryItem.addActionListener(e -> copySelectedRowField(1));
        popupMenu.add(copyCategoryItem);
        
        JMenuItem copyAuthorItem = new JMenuItem("复制作者");
        copyAuthorItem.addActionListener(e -> copySelectedRowField(3));
        popupMenu.add(copyAuthorItem);
        
        JMenuItem copyTranslatorItem = new JMenuItem("复制译者");
        copyTranslatorItem.addActionListener(e -> copySelectedRowField(4));
        popupMenu.add(copyTranslatorItem);
        
        JMenuItem copyPublisherItem = new JMenuItem("复制出版商");
        copyPublisherItem.addActionListener(e -> copySelectedRowField(5));
        popupMenu.add(copyPublisherItem);
        
        JMenuItem copyLanguageItem = new JMenuItem("复制语言");
        copyLanguageItem.addActionListener(e -> copySelectedRowField(6));
        popupMenu.add(copyLanguageItem);
    }

    // 复制选中行的ISBN到剪贴板
    private void copySelectedRowISBN() {
        copySelectedRowField(0);
    }
    
    // 复制选中行的指定列数据到剪贴板
    private void copySelectedRowField(int columnIndex) {
        int selRow = table.getSelectedRow();
        if (selRow < 0) {
            JOptionPane.showMessageDialog(this, "请先选择一行数据", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String fieldValue = table.getValueAt(selRow, columnIndex).toString().trim();
        StringSelection selection = new StringSelection(fieldValue);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
        
        String columnName = columnNames[columnIndex];
        JOptionPane.showMessageDialog(this, columnName + "已复制到剪贴板: " + fieldValue, "成功", JOptionPane.INFORMATION_MESSAGE);
    }

    // 筛选图书
    private void filterBooks() {
        Item selectedItem = (Item) bookTypeFilter.getSelectedItem();
        List<BookInfo> bookList;
        
        if (selectedItem.getId() == -1) { // 全部
            bookList = Dao.selectBookInfo();
        } else {
            bookList = Dao.selectBookCategory(selectedItem.toString());
        }
        
        Object[][] results = getFileStates(bookList);
        DefaultTableModel model = new DefaultTableModel(results, columnNames);
        table.setModel(model);
    }

    public class TableListener extends MouseAdapter {
        public void mouseClicked(final MouseEvent e) {
            // 处理左键点击显示详情
            if (e.getButton() == MouseEvent.BUTTON1) {
                int selRow = table.rowAtPoint(e.getPoint());
                if (selRow >= 0) {
                    table.setRowSelectionInterval(selRow, selRow);
                    showBookDetails(selRow);
                }
            } 
            // 处理右键点击显示菜单
            else if (e.getButton() == MouseEvent.BUTTON3) {
                int selRow = table.rowAtPoint(e.getPoint());
                if (selRow >= 0) {
                    table.setRowSelectionInterval(selRow, selRow);
                    popupMenu.show(table, e.getX(), e.getY());
                }
            }
        }

        // 显示图书详情
        private void showBookDetails(int selRow) {
            StringBuilder details = new StringBuilder();
            details.append("图书编号: ").append(table.getValueAt(selRow, 0)).append("\n");
            details.append("图书类别: ").append(table.getValueAt(selRow, 1)).append("\n");
            details.append("图书名称: ").append(table.getValueAt(selRow, 2)).append("\n");
            details.append("作者: ").append(table.getValueAt(selRow, 3)).append("\n");
            details.append("译者: ").append(table.getValueAt(selRow, 4)).append("\n");
            details.append("出版商: ").append(table.getValueAt(selRow, 5)).append("\n");
            details.append("语言: ").append(table.getValueAt(selRow, 6)).append("\n");
            details.append("出版日期: ").append(table.getValueAt(selRow, 7)).append("\n");
            details.append("价格: ").append(table.getValueAt(selRow, 8)).append("\n");
            details.append("库存数量: ").append(table.getValueAt(selRow, 9)).append("\n");
            
            JOptionPane.showMessageDialog(null, details.toString(), "图书详情", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}    